import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Form, 
  Input, 
  Select, 
  DatePicker, 
  Button, 
  Table, 
  Tag, 
  message, 
  Pagination,
  Space
} from 'antd';
import { 
  SearchOutlined, 
  SyncOutlined, 
  EyeOutlined, 
  EditOutlined 
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { getOrderList, getOrderDetail } from '@/api/account';

const { RangePicker } = DatePicker;
const { Option } = Select;

const OrderManagement = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [orderList, setOrderList] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 获取订单列表
  const fetchOrders = async () => {
    try {
      setLoading(true);
      const values = await form.validateFields();
      
      const params = {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
        ...values,
        date: values.dateRange ? JSON.stringify(values.dateRange.map(item => item.format('YYYY-MM-DD HH:mm:ss'))) : undefined
      };

      const res = await getOrderList(params);
      setOrderList(res.data);
      setPagination({
        ...pagination,
        total: res.total
      });
    } catch (error) {
      message.error('获取订单列表失败');
      console.error('获取订单列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 搜索方法
  const handleSearch = () => {
    setPagination({ ...pagination, current: 1 });
    fetchOrders();
  };

  // 重置搜索
  const resetSearch = () => {
    form.resetFields();
    handleSearch();
  };

  // 分页变化
  const handleTableChange = (pagination) => {
    setPagination(pagination);
    fetchOrders();
  };

  // 查看订单详情
  const handleView = async (record) => {
    try {
      const res = await getOrderDetail({ id: record.id });
      console.log('订单详情:', res.data);
      message.success(`查看订单 ${record.orderNo}`);
      // 这里可以打开详情弹窗或跳转到详情页
    } catch (error) {
      message.error('获取订单详情失败');
      console.error('获取订单详情失败:', error);
    }
  };

  // 编辑订单
  const handleEdit = (record) => {
    console.log('编辑订单:', record);
    message.success(`编辑订单 ${record.orderNo}`);
    // 这里可以打开编辑弹窗或跳转到编辑页
  };

  // 格式化日期
  const formatDate = (dateStr) => {
    if (!dateStr || dateStr === '0000-00-00 00:00:00') return '-';
    return dayjs(dateStr).format('YYYY-MM-DD HH:mm:ss');
  };

  // 根据状态获取标签类型
  const getStatusType = (status) => {
    switch (status) {
      case '已受理': return 'blue';
      case '已完成': return 'green';
      case '派送中': return 'orange';
      default: return 'gray';
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchOrders();
  }, [pagination.current, pagination.pageSize]);

  // 表格列定义
  const columns = [
    {
      title: '订单号',
      dataIndex: 'orderNo',
      width: 120,
    },
    {
      title: '下单时间',
      dataIndex: 'orderTime',
      width: 180,
      render: (text) => formatDate(text),
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      width: 130,
    },
    {
      title: '收货人',
      dataIndex: 'consignee',
      width: 100,
    },
    {
      title: '送货地址',
      dataIndex: 'deliverAddress',
      width: 150,
    },
    {
      title: '送达时间',
      dataIndex: 'deliveryTime',
      width: 180,
      render: (text) => formatDate(text),
    },
    {
      title: '备注',
      dataIndex: 'remarks',
      width: 100,
    },
    {
      title: '订单金额',
      dataIndex: 'orderAmount',
      width: 100,
      align: 'right',
      render: (text) => `¥${text.toFixed(2)}`,
    },
    {
      title: '订单状态',
      dataIndex: 'orderState',
      width: 100,
      render: (text) => <Tag color={getStatusType(text)}>{text}</Tag>,
    },
    {
      title: '操作',
      width: 150,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button 
            icon={<EyeOutlined />} 
            size="small" 
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button 
            icon={<EditOutlined />} 
            size="small" 
            type="primary"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 20 }}>
      <Card title="订单查询" style={{ marginBottom: 20 }}>
        <Form
          form={form}
          layout="inline"
        >
          <Form.Item name="orderNo" label="订单号">
            <Input placeholder="请输入订单号" allowClear />
          </Form.Item>
          <Form.Item name="consignee" label="收货人">
            <Input placeholder="请输入收货人" allowClear />
          </Form.Item>
          <Form.Item name="phone" label="手机号">
            <Input placeholder="请输入手机号" allowClear />
          </Form.Item>
          <Form.Item name="orderState" label="订单状态">
            <Select placeholder="请选择订单状态" allowClear style={{ width: 120 }}>
              <Option value="已受理">已受理</Option>
              <Option value="已完成">已完成</Option>
              <Option value="派送中">派送中</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dateRange" label="选择时间">
            <RangePicker 
              showTime={{ format: 'HH:mm:ss' }}
              format="YYYY-MM-DD HH:mm:ss"
              style={{ width: 350 }}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button 
                type="primary" 
                icon={<SearchOutlined />} 
                onClick={handleSearch}
              >
                搜索
              </Button>
              <Button 
                icon={<SyncOutlined />} 
                onClick={resetSearch}
              >
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>

      <Card title="订单列表">
        <Table
          columns={columns}
          dataSource={orderList}
          rowKey="id"
          bordered
          loading={loading}
          pagination={false}
          scroll={{ x: 1500 }}
        />
        <div style={{ marginTop: 20, textAlign: 'right' }}>
          <Pagination
            {...pagination}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `共 ${total} 条`}
            onChange={(page, pageSize) => handleTableChange({ ...pagination, current: page, pageSize })}
            onShowSizeChange={(current, size) => handleTableChange({ ...pagination, current: 1, pageSize: size })}
          />
        </div>
      </Card>
    </div>
  );
};

export default OrderManagement;